﻿using Newtonsoft.Json;
using PanhuaWin.NCModel;
using PanhuaWin.WMS2NC888;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PanhuaWin.工厂.仓库.原料辅材推送NC
{
    public partial class Form辅材推送NC : UIPage
    {
        public Form辅材推送NC()
        {
            InitializeComponent();
            uiDataGridView辅料.AutoGenerateColumns = false;
        }

        private void uiButton合同查询_Click(object sender, EventArgs e)
        {
            queryStockInM();
        }

        private void queryStockInM()
        {
            String sql = @"select [Bus_StockOutM].guid, StockOutType, [Bus_StockOutM].WorkShopCode, WorkShopName, 
                        [Bus_StockOutM].DocCode, DepartCode, DepartName, WorkLineCode, 
                        WorkLineName, CreateID, Creator, CreateDate, ModifyID, Modifier, ModifyDate, ApproverID, Approver,
                        ApproverDate, 
                        Bguid,  RowNumber,  WarehouseCode, StorageLocation, InventoryCode, Size, 
                        Batch, QuantityMain, QuantityAssist, [Bus_StockOutMaterial].IsSendToNC, SendToNCResult, [Bus_StockOutMaterial].SendToNCDate
                        from
                        [Bus_StockOutM]
                        left join [dbo].[Bus_StockOutMaterial] on [Bus_StockOutMaterial].guid = [Bus_StockOutM].guid where 1=1 ";
            if (uiRadioButton已推送.Checked)
            {
                sql += " and [Bus_StockOutMaterial].IsSendToNC = 'Y'";
            }
            if (uiRadioButton未推送.Checked)
            {
                sql += " and ( [Bus_StockOutMaterial].IsSendToNC = 'N' OR [Bus_StockOutMaterial].IsSendToNC IS NULL )";
            }
            sql += " and T_GOOD_NAME = '锌锭' ";

            DataTable dt = pub.GetDataTable(pub.ConnectionString, sql);
            uiDataGridView辅料.DataSource = dt;
            uiDataGridView辅料.Refresh();
        }

        private void uiButton推送NC_Click(object sender, EventArgs e)
        {
            string logsql = @"insert into Sys_Log( BeginDate, BrowserType, RequestParameter,UserName, User_Id ,UserIP,ServiceIP   )";
            logsql += "values(getdate(),'WinForm','调用NCservice','" + pub.sys_user.UserName + "','" + pub.sys_user.User_Id + "','" + MAC.getIP.getLocalIP() + "','WMS2NC888')";
            pub.ExecuteSql(pub.ConnectionString, logsql);

            if (uiDataGridView辅料.Rows != null && uiDataGridView辅料.Rows.Count > 0)
            {
                for (int i = 0; i < uiDataGridView辅料.Rows.Count; i++)
                {
                    string guid = uiDataGridView辅料.Rows[i].Cells["Cguid"].Value.ToString();
                    NCResponseModel nCResponse = send原来领用ToNC(guid);
                    //调用成功，改写NC状态
                    //if (nCResponse.state == 0)
                    //{
                    //    //更新出库表
                    //    string sqlUpdate = @"update Bus_StockOutMaterial set IsSendToNC = 'Y',SendToNCResult = '" + nCResponse.result + "' ,SendToNCDate = '"
                    //                        + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where guid = '" + guid + "'";
                    //    int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                    //    uiDataGridView辅料.Rows[i].Cells["CIsSendToNC"].Value = "Y";
                    //    if (r < 1)
                    //    {
                    //        MessageBox.Show("发送NC成功，更新数据库失败");
                    //    }
                    //}
                    //else
                    //{
                    //    string sqlUpdate = @"update Bus_StockOutMaterial set IsSendToNC = 'N',SendToNCResult = '" + nCResponse.msg + "' ,SendToNCDate = '"
                    //                        + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where guid = '" + guid + "'";
                    //    int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                    //    uiDataGridView辅料.Rows[i].Cells["CIsSendToNC"].Value = "N";
                    //    if (r < 1)
                    //    {
                    //        MessageBox.Show("发送NC失败，更新数据库失败");
                    //    }
                    //}
                }
            }
        }
    

    private NCResponseModel send原来领用ToNC(string guid)
    {
        NCModel.NCResponseModel nCResponse = new NCResponseModel();
        //查询领用出库单
        string sqlHeader = @"SELECT   guid, StockOutType, WorkShopCode, WorkShopName, DocCode, DepartCode, DepartName, WorkLineCode, 
                               WorkLineName, CreateID, Creator, CreateDate, ModifyID, Modifier, ModifyDate, ApproverID, Approver, ApproverDate, 
                               IsSendToNC, SendToNCDate
                                FROM      Bus_StockOutM where guid = '" + guid + "'";
        DataTable dtHeader = pub.GetDataTable(pub.ConnectionString, sqlHeader);
        if (dtHeader != null && dtHeader.Rows.Count > 0)
        {

            //头
            string region = "华中";//地区
            string createdate = DateTime.Parse(dtHeader.Rows[0]["CreateDate"].ToString()).ToString("yyyy-MM-dd");
            string WorkShopCode = dtHeader.Rows[0]["WorkShopCode"].ToString();//公司编号
            string corpName = "";
            string cWhsmanagerCode = dtHeader.Rows[0]["Creator"].ToString();
            string cbizCode = dtHeader.Rows[0]["Creator"].ToString(); //业务员编码 
            //string wareHouseCode = "FYLK";
            string cWarehouseName = "";
                //公司名称 对应 产线名称
                string deptName = dtHeader.Rows[0]["WorkLineName"].ToString();

            //查询公司名称 公司编号
            string sqlworkshop = @"SELECT  [WorkShopName]  FROM [Dic_WorkShop] where WorkShopCode = '" + WorkShopCode + "'";
            DataTable dtWorkShop = pub.GetDataTable(pub.ConnectionString, sqlworkshop);
            if (dtWorkShop != null && dtWorkShop.Rows.Count > 0)
            {
                corpName = dtWorkShop.Rows[0]["WorkShopName"].ToString();
            }

                ////查仓库名称
                //string sqlwareName = "select WarehouseName from Dic_Warehouse where WarehouseCode = '" + wareHouseCode + "'";

                //DataTable dtWareName = pub.GetDataTable(pub.ConnectionString, sqlwareName);
                //if (dtWareName != null && dtWareName.Rows.Count > 0)
                //{
                //    cWarehouseName = dtWareName.Rows[0]["WarehouseName"].ToString();
                //}

                //NC对象
                MaterialOutBillModel materialOutBillModel = new MaterialOutBillModel();
                materialOutBillModel.region = region;
                materialOutBillModel.createdate = createdate;
                materialOutBillModel.corpName = corpName;
                materialOutBillModel.cwhsmanagercode = cWhsmanagerCode;
                materialOutBillModel.cbizCode = cbizCode;
                materialOutBillModel.deptName = deptName;
                //materialOutBillModel.outhouseName = cWarehouseName;
                materialOutBillModel.remarks = "";

            //查表体
            string sqlBody = @"SELECT   guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, InventoryCode, Size, 
                                   Batch, QuantityMain, QuantityAssist
                                   FROM  Bus_StockOutMaterial where guid = '" + guid + "' and (IsSendToNC <> 'Y' or IsSendToNC is null)";
            DataTable dtBody = pub.GetDataTable(pub.ConnectionString, sqlBody);


                //List<MaterialOutBillItemModel> items = new List<MaterialOutBillItemModel>();
                if (dtBody != null && dtBody.Rows.Count > 0)
                {
                    for (int i = 0; i < dtBody.Rows.Count; i++)
                    {
                        List<MaterialOutBillItemModel> items = new List<MaterialOutBillItemModel>();
                        //体
                        //查仓库名称
                        string wareHouseCode = dtBody.Rows[i]["WarehouseCode"].ToString();
                        string sqlwareName = "select WarehouseName from Dic_Warehouse where WarehouseCode = '" + wareHouseCode + "'";

                        DataTable dtWareName = pub.GetDataTable(pub.ConnectionString, sqlwareName);
                        if (dtWareName != null && dtWareName.Rows.Count > 0)
                        {
                            cWarehouseName = dtWareName.Rows[0]["WarehouseName"].ToString();
                        }
                        materialOutBillModel.outhouseName = cWarehouseName;

                        string rowNo = dtBody.Rows[i]["Bguid"].ToString(); //明细ID
                        string cinvbascode = dtBody.Rows[i]["InventoryCode"].ToString(); //存货编码
                        string vbatchcode = dtBody.Rows[i]["Batch"].ToString(); //批次号
                        string nnum = dtBody.Rows[i]["QuantityMain"].ToString(); //入库数量
                        string dbilldate = createdate;//入库日期
                        //string vuserdef9 = dtBody.Rows[i]["StorageLocation"].ToString();//库位号
                        string vuserdef9 = "";
                        MaterialOutBillItemModel materialOutBillItemModel = new MaterialOutBillItemModel();
                        materialOutBillItemModel.rowNo = rowNo;
                        materialOutBillItemModel.cinvbascode = cinvbascode;
                        materialOutBillItemModel.vbatchcode = vbatchcode;
                        materialOutBillItemModel.nnum = nnum;
                        materialOutBillItemModel.dbilldate = dbilldate;
                        materialOutBillItemModel.vuserdef9 = vuserdef9;
                        materialOutBillItemModel.vfree1 = "";
                        materialOutBillItemModel.vfree2 = "";
                        materialOutBillItemModel.vfree3 = "";
                        materialOutBillItemModel.vfree4 = "";
                        materialOutBillItemModel.vfree5 = "";
                        materialOutBillItemModel.pk_defdoc11 = "";
                        materialOutBillItemModel.pk_defdoc12 = "";
                        materialOutBillItemModel.vnotebody = "";
                        materialOutBillItemModel.vuserdef8 = "";
                        materialOutBillItemModel.vuserdef10 = "";
                        materialOutBillItemModel.pk_defdoc13 = "";

                        items.Add(materialOutBillItemModel);
                        materialOutBillModel.items = items;
                        string jsonStr = JsonConvert.SerializeObject(materialOutBillModel);
                        ExternalSystemToNcItfPortTypeClient client = new ExternalSystemToNcItfPortTypeClient();
                        string responseStr = client.materialOutBill(jsonStr);
                        nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                        //调用成功，改写NC状态
                        if (nCResponse.state == 0)
                        {
                            //更新出库表
                            string sqlUpdate = @"update Bus_StockOutMaterial set IsSendToNC = 'Y',SendToNCResult = '" + nCResponse.result + "' ,SendToNCDate = '"
                                                + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where Bguid = '" + rowNo + "'";
                            int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                            if (r < 1)
                            {
                                MessageBox.Show("更新成功发送到NC失败");
                            }
                        }
                        else
                        {
                            string sqlUpdate = @"update Bus_StockOutMaterial set IsSendToNC = 'N',SendToNCResult = '" + nCResponse.msg + "' ,SendToNCDate = '"
                                                + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where Bguid = '" + rowNo + "'";
                            int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                            if (r < 1)
                            {
                                MessageBox.Show("更新失败发送到NC失败");
                            }
                        }
                    }
                }
                //if (items != null && items.Count > 0)
                //{
                //string jsonStr = JsonConvert.SerializeObject(materialOutBillModel);
                //WMS2NCTest.ExternalSystemToNcItfPortTypeClient client = new WMS2NCTest.ExternalSystemToNcItfPortTypeClient();
                //string responseStr = client.materialOutBill(jsonStr);
                //nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                ////调用成功，改写NC状态
                ////if (nCResponse.state == 0)
                ////{
                ////    //更新出库表
                ////    string sqlUpdate = @"update Bus_StockOutMaterial set IsSendToNC = 'Y',SendToNCResult = '" + nCResponse.result + "' ,SendToNCDate = '"
                ////                        + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where guid = '" + guid + "'";
                ////    int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                ////    if (r < 1)
                ////    {
                ////        MessageBox.Show("更新成功发送到NC失败");
                ////    }
                ////}
                ////else
                ////{
                ////    string sqlUpdate = @"update Bus_StockOutMaterial set IsSendToNC = 'N',SendToNCResult = '" + nCResponse.msg + "' ,SendToNCDate = '"
                ////                        + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where guid = '" + guid + "'";
                ////    int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                ////    if (r < 1)
                ////    {
                ////        MessageBox.Show("更新失败发送到NC失败");
                ////    }
                ////}
                //}

            }
        return nCResponse;
    }

        private void uiButton匹配存货编号_Click(object sender, EventArgs e)
        {
            if (uiDataGridView辅料.Rows != null && uiDataGridView辅料.Rows.Count > 0)
            {
                for (int i = 0; i < uiDataGridView辅料.Rows.Count; i++)
                {
                    string bguid = uiDataGridView辅料.Rows[i].Cells["Cbguid"].Value.ToString();
                    string sqlBody = @"SELECT   guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, InventoryCode, Size, 
                                   Batch, QuantityMain, QuantityAssist
                                   FROM  Bus_StockOutMaterial where Bguid = '"+ bguid + "'";
                    DataTable dt = pub.GetDataTable(pub.ConnectionString,sqlBody);
                    string NC存货编号 = pub.GetInventoryCode("锌锭", dt.Rows[0]["Size"].ToString());
                    //更新
                    string sqlupdate = "update Bus_StockOutMaterial set InventoryCode = '" + NC存货编号 + "' where Bguid = '" + bguid + "'";
                    int r = pub.ExecuteSql(pub.ConnectionString, sqlupdate, "");
                }
            }
        }
    }

}
